package com.hujiang.basic.search.search.service;

import com.hujiang.basic.search.api.SearchService;
import com.hujiang.basic.search.common.component.HJElasticSearchClient;
import com.hujiang.basic.search.common.converter.req.GetRequestConverter;
import com.hujiang.basic.search.common.converter.req.SearchRequestConverter;
import com.hujiang.basic.search.common.converter.req.SuggestRequestConverter;
import com.hujiang.basic.search.common.converter.resp.SearchHitsConverter;
import com.hujiang.basic.search.common.converter.resp.SuggestHitsConverter;
import com.hujiang.basic.search.model.*;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.suggest.SuggestRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;


@Service
public class SearchServiceImpl implements SearchService {

    @Resource(name = "hJElasticSearchClient")
    private HJElasticSearchClient elasticSearchClient;

    @Autowired
    private SearchRequestConverter searchConverter;

    @Autowired
    private SuggestRequestConverter suggestConverter;

    @Autowired
    private SearchHitsConverter searchHitsConverter;

    @Autowired
    private SuggestHitsConverter suggestHitsConverter;

    @Autowired
    private GetRequestConverter getConverter;

    @Override
    public HJSearchResponse search(HJSearchRequest hjSearchRequest) {
        SearchRequest raw = searchConverter.convert(hjSearchRequest);
        return searchHitsConverter.convert(elasticSearchClient.search(raw), hjSearchRequest);
    }

    @Override
    public HJSuggestResponse suggest(HJSuggestRequest hjSuggestRequest) {
        SuggestRequest raw = suggestConverter.convert(hjSuggestRequest);
        return suggestHitsConverter.convert(elasticSearchClient.suggest(raw));
    }

    @Override
    public Map<String, Object> get(HJGetRequest request) {
        GetRequest raw = getConverter.convert(request);
        return elasticSearchClient.get(raw).getSource();
    }
}
